import { useEffect, useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Order } from "@/types/order";
import { orderService } from "@/service/orderService";
import { toast } from "sonner";
import { OrderCard } from "@/components/website/OrderCard";
import { payService } from "@/service/payService";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";



export default function Orders() {
  // 模拟订单数据
  const [orders, setOrders] = useState<Order[]>([]);
  const [showSuccessDialog, setShowSuccessDialog] = useState(false);



  const fetchOrders = async () => {
    orderService.orderList().then(data => {
      if (data) {
        setOrders(data);
      } else {
        toast.error("获取订单列表失败");
      }
    })
  }


  useEffect(() => { fetchOrders(); }, []);


  const handlePayment = async (orderId: number) => {
    const paymentHtml = await payService.requestPayment(orderId);
    if (!paymentHtml) {
      toast.error("支付请求失败，请稍后重试");
      return;
    }
    const paymentWindow = window.open("", "_blank");
    if (paymentWindow) {
      paymentWindow.document.writeln(paymentHtml);
      paymentWindow.document.close();
      setShowSuccessDialog(true);
    }

  }


  const handleCancel = async (orderId: number) => {
    const response = await orderService.cancelOrder(orderId);
    if (response) {
      toast.success("订单已取消");
    } else {
      toast.error("取消订单失败，请稍后重试");
    }
    fetchOrders();
  }



  const handleReceived = async (orderId: number) => {
    const response = await orderService.receivedOrder(orderId);
    if (response) {
      toast.success("订单已确认收货");
    } else {
      toast.error("确认收货失败，请稍后重试");
    }
    fetchOrders();
  }



  // 根据状态过滤订单
  const filteredOrders = (status: string) => {
    const filtered = orders.filter(order => order.status === status || status === "all");;
    if (filtered.length == 0)
      return (
        <div className="text-center py-12">
          <p className="text-muted-foreground">暂无订单</p>
        </div>
      );
    return filtered.map(order => <OrderCard order={order} key={order.id} onCancel={handleCancel} onPayment={handlePayment} onReceived={handleReceived} />);
  };


  return (
    <div className="max-w-6xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">我的订单</h1>

      <Tabs defaultValue="all">
        <TabsList className="mb-6">
          <TabsTrigger value="all">全部</TabsTrigger>
          <TabsTrigger value="pending">待支付</TabsTrigger>
          <TabsTrigger value="paid">已支付</TabsTrigger>
          <TabsTrigger value="shipped">已发货</TabsTrigger>
          <TabsTrigger value="delivered">已送达</TabsTrigger>
          <TabsTrigger value="completed">已完成</TabsTrigger>
        </TabsList>

        <TabsContent value="all" >
          {filteredOrders("all")}
        </TabsContent>

        <TabsContent value="pending">
          {filteredOrders("pending")}
        </TabsContent>

        <TabsContent value="paid">
          {filteredOrders("paid")}
        </TabsContent>

        <TabsContent value="shipped">
          {filteredOrders("shipped")}
        </TabsContent>

        <TabsContent value="delivered">
          {filteredOrders("delivered")}
        </TabsContent>

        <TabsContent value="completed">
          {filteredOrders("completed")}
        </TabsContent>
      </Tabs>



      <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>提交成功</DialogTitle>
          </DialogHeader>
          <DialogDescription className="text-center py-4">
            支付页面已在新标签页中打开
          </DialogDescription>
          <DialogFooter className="sm:justify-center">
            <Button onClick={() => { setShowSuccessDialog(false); fetchOrders(); }}>
              支付成功，点击刷新
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>




    </div>
  );
} 